﻿using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine; 

namespace XFGameFramework.Localization
{
    public class LocalizationConfigsWindow : SplitWindow
    {

        [MenuItem("Window/XFKT/XFGameFramework/InstalledExtension/Localization/多语言配置窗口", false, 10)]
        static void Open()
        {
            GetWindow<LocalizationConfigsWindow>().Show();
        }

        #region 字段

        private const string SELECT_GUID_KEY = "LOCALIZATION_SELECT_GUID_KEY"; 

        //private Rect left;

        private GUIContent currentMultiLanguageConfigContent;

        private string searchStr;
         
        [SerializeField]
        private TreeViewStateGroup treeViewStateGroup = new TreeViewStateGroup();

#if UNITY_6000_2_OR_NEWER
        private TreeViewState<int> languageListState => treeViewStateGroup.Get(currentMultiLanguageConfig.GetHashCode());

#else
        private TreeViewState languageListState => treeViewStateGroup.Get(currentMultiLanguageConfig.GetHashCode());
#endif

        internal LanguageListTree languageListTree;

#if UNITY_6000_2_OR_NEWER
        public TreeViewState<int> languageInfoState;
#else
        public TreeViewState languageInfoState;
#endif


        internal MultiLanguageConfigs currentMultiLanguageConfig; 

        private float timer = 0;

        internal SystemLanguage currentShowLanuage = 0;
         
        private float lastRepaintCount = 0;

        private int currentID;
        public int idChangeCount;

#endregion


        #region 属性

        internal static string SelectGUID
        {
            get
            {
                return EditorPrefs.GetString(SELECT_GUID_KEY);
            }
            set
            {
                EditorPrefs.SetString(SELECT_GUID_KEY, value);
            } 
        }

        #endregion


        #region 生命周期

        private void Awake()
        {
            titleContent = new GUIContent("多语言配置窗口", "多语言配置窗口"); 
        }
         

        private void Update()
        {
            lastRepaintCount++;
            if (lastRepaintCount > 15) { 
                Repaint();
                lastRepaintCount = 0;
            }

        }

        protected override void OnGUI()
        { 
            if (Time.realtimeSinceStartup - timer > 1 && currentMultiLanguageConfig == null)
            {
                currentMultiLanguageConfig = GetCurrentConfig();
                timer =  Time.realtimeSinceStartup;
            }

            if (currentMultiLanguageConfig == null)
            {
                EmptyGUI();
            }
            else
            {
                base.OnGUI();
            }
        }


        #endregion


        #region 方法

        internal MultiLanguageConfigs GetCurrentConfig()
        {
            if (!string.IsNullOrEmpty(SelectGUID))
            {
                string asset_path = AssetDatabase.GUIDToAssetPath(SelectGUID);
                MultiLanguageConfigs config = AssetDatabase.LoadAssetAtPath<MultiLanguageConfigs>(asset_path);
                if(config != null) return config;
            }

            List<MultiLanguageConfigs> configs = MultiLanguageConfigsController.GetAllMultiLanguageConfigs();

            if (configs == null || configs.Count == 0)
                return null;
             
            SelectGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(configs[0]));
            //RefreshCurrentMultiLanguageConfig(configs[0]);
            return configs[0];
        }

        protected override void DrawGUILeft(Rect rect)
        {
            base.DrawGUILeft(rect);
            GUILayout.BeginArea(rect);
            DrawLeft(rect);
            GUILayout.EndArea();
        }

        protected override void DrawGUIRight(Rect rect)
        {
            base.DrawGUIRight(rect);

            GUILayout.BeginArea(rect);
            DrawRight();
            GUILayout.EndArea();

        }

        private void EmptyGUI()
        {

            GUILayout.BeginHorizontal();

            GUILayout.FlexibleSpace();

            GUILayout.BeginVertical();
            GUILayout.FlexibleSpace();
            GUILayout.Label("未查询到多语言配置文件!");
            if (GUILayout.Button("立即创建"))
            {
                CreateNew();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

        }
      
        private void DrawLeft(Rect left)
        {
            if (currentMultiLanguageConfigContent == null)
                currentMultiLanguageConfigContent = new GUIContent();

            if (currentMultiLanguageConfig == null)
                return;
             
            currentMultiLanguageConfigContent.text = GetMultiLanguageConfigsDisplayName(currentMultiLanguageConfig);
          
  
            currentMultiLanguageConfigContent.tooltip = AssetDatabase.GetAssetPath(currentMultiLanguageConfig);

            GUILayout.BeginHorizontal();
            // 

            EditorGUI.BeginChangeCheck();

            searchStr = EditorGUILayout.TextField(string.Empty,searchStr, "SearchTextField",GUILayout.MinWidth(0));

            if (EditorGUI.EndChangeCheck())
            {
                if (string.IsNullOrEmpty(searchStr) && languageListTree.state.selectedIDs.Count > 0)
                {
                    EditorApplication.delayCall += () =>
                    {
                        languageListTree.FrameItem(languageListTree.state.selectedIDs[0]);
                    };
                }
            }

            if (EditorGUILayout.DropdownButton(currentMultiLanguageConfigContent, FocusType.Passive, EditorStyles.toolbarDropDown, GUILayout.Width(this.position.width * 0.35f * 0.3f)))
            {

                List<MultiLanguageConfigs> configs = MultiLanguageConfigsController.GetAllMultiLanguageConfigs();

                GenericMenu menu = new GenericMenu();

                foreach (var item in configs)
                {
                    string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(item));
                    bool isOn = SelectGUID == guid;

                    menu.AddItem(new GUIContent(GetMultiLanguageConfigsDisplayName(item)), isOn, () =>
                    {
                        EditorGUIUtility.PingObject(item);
                        GUI.FocusControl(null);
                         
                        if (!isOn) 
                        {
                            SetCurrentConfigs(item);
                        } 
                    });
                }

                menu.AddSeparator(string.Empty);

                menu.AddItem(new GUIContent("新建多语言配表"), false, () =>
                {
                    CreateNew();
                });

                menu.ShowAsContext();
            }

            GUILayout.EndHorizontal();
             
            if (languageListTree == null)
            {
                languageListTree = new LanguageListTree(languageListState, currentMultiLanguageConfig);  
            } 
             
            languageListTree.searchString = searchStr;

            left.Set(left.x, left.y + 20, left.width, left.height - 20);
            languageListTree.OnGUI(left);


            if (languageListTree != null && languageListTree.MultiLanguageConfig != currentMultiLanguageConfig)
            { 
                languageListTree = null; 
                languageInfoState = null;
            }
        }

        private void DrawRight()
        {
            if (languageInfoState == null)
            {
#if UNITY_6000_2_OR_NEWER
                languageInfoState = new TreeViewState<int>();
#else
                languageInfoState = new TreeViewState();
#endif

            }

            // 判断是否为空 

            if (languageListTree != null)
            {

                if (languageListState.selectedIDs.Count > 1)
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    Color origin = GUI.color;
                    GUI.color = Color.yellow;
                    GUILayout.Label("不支持同时编辑多个配置!");
                    GUI.color = origin;
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();
                    GUILayout.FlexibleSpace();
                }
                else if (languageListState.selectedIDs.Count == 1)
                {
                    DrawData(); 
                }
                else
                {
                    GUILayout.FlexibleSpace();
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();
                    GUILayout.Label("空");
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();
                    GUILayout.FlexibleSpace();
                }
            }
            else 
            {

                GUILayout.FlexibleSpace();
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                GUILayout.Label("空!");
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
                GUILayout.FlexibleSpace();

            } 
        }

        private void DrawData()
        {
            int id = languageListState.selectedIDs[0];

            if (currentID != id)
            {
                idChangeCount++;
                if (idChangeCount > 1)
                {
                    // 如果当前帧是Layout ，不能设置，因为当前帧会被return 
                    // 如果当前帧被return , 下一帧repaint 会报错，因为没有位置数据
                    if (Event.current.type != EventType.Layout) 
                    { 
                        currentID = id;
                        idChangeCount = 0;
                    } 
                }
                // 这样处理的目的是 为了防止 EditorGUILayout.DelayedIntField 在编辑时 ,
                // 直接切换id,  EditorGUILayout.DelayedIntField  返回的值会直接给新选中的数据， 导致数据错误的情况
                return;
            }
             
            currentShowLanuage = (SystemLanguage)id; 
            LanguageConfig data = currentMultiLanguageConfig.GetLanguageConfigData(currentShowLanuage);
            LanguageConfigsInspector.Instance.OnInspectorGUI(data, this, currentMultiLanguageConfig);
        }


        private string GetMultiLanguageConfigsDisplayName(MultiLanguageConfigs configs) 
        { 
            if (string.IsNullOrEmpty(configs.displayName))
                return configs.name;
            else
              return string.Format("{0}({1})", configs.name, configs.displayName); 
        }
 
        //internal void RefreshCurrentMultiLanguageConfig(MultiLanguageConfigs item)
        //{ 
        //    foreach (var s in item.Languages)
        //    {
        //        if (s == null) continue;
        //        RefreshCurrentLanguageConfig(s.language);
        //        return;
        //    }

        //    RefreshCurrentLanguageConfig(SystemLanguage.Unknown);
        //}

        //internal void RefreshCurrentLanguageConfig(SystemLanguage language)
        //{
        //    //Debug.LogFormat("刷新语言:{0}", language);
        //    currentMultiLanguageConfig = GetCurrentConfig();
          
        //    if (languageListTree != null) 
        //    {
        //        languageListTree.Reload();
              
        //        if (language != SystemLanguage.Unknown)
        //            languageListTree.SetSelection(new int[] { (int)language });
        //    }
             
        //}

        internal bool IsEmpty()
        {
            if (currentMultiLanguageConfig == null)
                return true;

            bool isRemove = false;

            for (int i = 0; i < currentMultiLanguageConfig.Languages.Count; i++)
            {
                if (currentMultiLanguageConfig.Languages[i] == null) 
                {
                    currentMultiLanguageConfig.Languages.RemoveAt(i);
                    i--;
                    EditorUtility.SetDirty(currentMultiLanguageConfig);
                    isRemove = true;
                } 
            }

            if (isRemove) 
            {
                AssetDatabase.SaveAssets();
            }

            for (int i = 0; i < currentMultiLanguageConfig.Languages.Count; i++)
            { 
                if (currentMultiLanguageConfig.Languages[i] != null)
                    return false;
            }


            return true;
        }

        public void SetCurrentConfigs(MultiLanguageConfigs item) 
        {
            currentID = -1;
            currentMultiLanguageConfig = item;
            SelectGUID = AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath(item));
            if (languageListTree != null)
            {
                languageListTree.Reload();
            }
        }

#endregion


        #region 创建

        private void CreateNew()
        {
            string path = EditorUtility.OpenFolderPanel("请选择文件夹", Application.dataPath, string.Empty);

            if (string.IsNullOrEmpty(path)) return;

            if (path.StartsWith(Application.dataPath))
            {
                path = path.Replace(Application.dataPath, string.Empty);
                path = string.Format("Assets{0}", path); 
                MultiLanguageConfigs skillsConfig = CreateInstance<MultiLanguageConfigs>();
                MultiLanguageConfigsController.CreateAsset(skillsConfig, path);

                SelectGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(skillsConfig));

                if (languageListTree != null)
                    languageListTree.Reload();

            }
            else
            {
                this.ShowNotification(new GUIContent("请把资源保存到Assets目录下!"));
            }
        }

        //public void CreateAsset(ScriptableObject scriptableObject, string path, bool ping = true)
        //{
        //    if (!System.IO.Directory.Exists(path)) { 
        //        System.IO.Directory.CreateDirectory(path);
        //        AssetDatabase.Refresh();
        //    }

        //    string name = GetName(scriptableObject.GetType().Name, path);
        //    AssetDatabase.CreateAsset(scriptableObject, string.Format("{0}/{1}.asset", path, name));
        //    Selection.activeObject = scriptableObject;
        //    if (ping)
        //    {
        //        SelectGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(scriptableObject));
        //        EditorGUIUtility.PingObject(scriptableObject);

        //        if(languageListState != null)
        //            languageListTree.Reload(); 
        //    }

        //    if (!Application.isPlaying)
        //    {
        //        LocalizationManager.Configs.Clear();
        //    }
        //}

    
        #endregion

          
    }

}

